var app = getApp();
var Zan = require('../../dist/index');
var Util = require('../../utils/util.js');

Page(Object.assign({}, Zan.TopTips, {

	data: {
		title: '',
		subtitle: '加载中...',
		type: 'coupon/list',
		loading: true,
		hasMore: true,
		page: 1,
		size: 20,
		records: []
	},

	loadMore: function () {
		var that = this;

		if (!this.data.hasMore) return;

		this.setData({subtitle: '加载中...', loading: true});

		return app.battery.find(this.data.type, this.data.page, this.data.size).then(function (d) {
			// if (d.list && d.list.length) {
			var _records = [];
			for (var i in d.list) {
				_records.push({
					id: d.list[i].id,
					status: d.list[i].status,
					name: d.list[i].name,
					money: d.list[i].money,
					endTime: Util.formatDate(new Date(d.list[i].endTime), 'yyyy-MM-dd HH:mm:ss')
				});
			}

			if (d.list.length < that.data.size) {
				that.setData({
					subtitle: '没有更多了',
					records: that.data.records.concat(_records),
					page: that.data.page++,
					hasMore: false,
					loading: false
				});
			} else {
				that.setData({
					subtitle: '下拉加载更多',
					page: that.data.page++,
					records: that.data.records.concat(_records),
					loading: false
				});
			}
			// }
		}).catch(function (e) {
			// that.setData({ subtitle: '获取数据异常', loading: false });
			console.error(e);
		});
	},

	onPullDownRefresh: function () {
		this.setData({records: [], page: 1, hasMore: true});
		this.loadMore().then(function () {
			return app.wechat.original.stopPullDownRefresh();
		});
	},

	onReachBottom: function () {
		this.loadMore();
	},

	onLoad: function (options) {

	},

	showTopTips: function (msg) {
		this.showZanTopTips(msg);
	},

	onShow: function () {
		this.loadMore();
	},

	onHide: function () {

	}
}));